package com.pinyoumei.app.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.LuckPanActivity;
import com.pinyoumei.app.activity.ProductDetailActivity;
import com.pinyoumei.app.activity.ProductDetailPtActivity;
import com.pinyoumei.app.adapter.BottomFirstNewAdapter;
import com.pinyoumei.app.adapter.GoodsIndexNewAdapter;
import com.pinyoumei.app.bean.FirstloadNewBean;
import com.pinyoumei.app.bean.GoodDetailsBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.ItemOffsetDecoration;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.view.GridSpacingItemDecoration;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.StaggeredDividerItemDecoration;
import com.pinyoumei.app.view.WrapContentHeightViewPager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GoodsIndexFragment extends Fragment {
    RecyclerView recyclerView;
    private GoodsIndexNewAdapter bottomFirstAdapter;
    String mPosition = "";
    String mTitle = "";
    private Gson gson;
    private List<FirstloadNewBean.FirstloadNewDto> listBeans = new ArrayList<>();
    private int page = 1;

    private int fragmentID=0;

    private  WrapContentHeightViewPager viewPager=null;

    public GoodsIndexFragment(WrapContentHeightViewPager vp, int fragmentID)
    {
        this.viewPager = vp;
        this.fragmentID =fragmentID;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_tab, null);
        viewPager.setObjectForPosition(view,fragmentID);
        gson = new Gson();
        mPosition = getArguments().getString("position");
        mTitle = getArguments().getString("title");
        RecyclerView rv_waterfall = view.findViewById(R.id.rv_bottom);
        rv_waterfall.setHasFixedSize(true);
        rv_waterfall.setItemAnimator(null);
        //垂直方向的2列
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //防止Item切换
//        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        rv_waterfall.setLayoutManager(layoutManager);
        final int spanCount = 2;
        rv_waterfall.addItemDecoration(new StaggeredDividerItemDecoration(getContext(),10,spanCount));

        bottomFirstAdapter = new GoodsIndexNewAdapter(getContext());
        rv_waterfall.setAdapter(bottomFirstAdapter);
        EventBusUtils.register(this);
        //解决底部滚动到顶部时，顶部item上方偶尔会出现一大片间隔的问题
        rv_waterfall.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                int[] first = new int[spanCount];
                layoutManager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    layoutManager.invalidateSpanAssignments();
                }
            }
        });
        bottomFirstAdapter.setOnItemClickLitener(new GoodsIndexNewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                if(TextUtils.equals(listBeans.get(position).getId(),"-1")){
                    startActivity(new Intent(getActivity(), LuckPanActivity.class));
                }else {
                    InitGoodDate(listBeans.get(position).getId());
                }
            }
        });
        LoadMoreData();

        return view;
    }

    private void LoadMoreData() {
        Map<String, Object> map = new HashMap<>();
        map.put("goods_type_id",mPosition);
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", page);
        map.put("limit", 8);
        OkGo.<String>post(Constants.HOME_DATA_LOADMORE_NEW)
                .params("goods_type_id", mPosition)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", page)
                .params("limit", 8)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    private void setData(Response<String> response) {
                        FirstloadNewBean firstloadBean = gson.fromJson(response.body(), FirstloadNewBean.class);
                        if (firstloadBean.getCode() >= 0) {
                            if(firstloadBean.getResult().getGoods_list() != null) {
                                if(page == 1){
                                    listBeans.clear();
                                    FirstloadNewBean.FirstloadNewDto firstloadNewDto = new FirstloadNewBean.FirstloadNewDto();
                                    firstloadNewDto.setId("-1");
                                    listBeans.add(0, firstloadNewDto);
                                }
                                listBeans.addAll(firstloadBean.getResult().getGoods_list());
                                bottomFirstAdapter.replaceAll(listBeans);
                                bottomFirstAdapter.notifyDataSetChanged();
                            }
                        } else {
                            Toast.makeText(getActivity(), firstloadBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }

    private void InitGoodDate(String goods_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("goods_id", goods_id);


        OkGo.<String>post(Constants.GOODS_LIST_DETAIL)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("goods_id", goods_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    private void setData(Response<String> response) {
                        GoodDetailsBean goodDetailsBean = gson.fromJson(response.body(), GoodDetailsBean.class);

                        if (goodDetailsBean.getCode() >= 0) {
                            Utils.isActivity = "1";
                            if (goodDetailsBean.getResult().getData_info().getIs_can_pt() == 1) {
                                Intent intent = new Intent(getActivity(), ProductDetailPtActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            }

                        } else {
                            Toast.makeText(getActivity(), goodDetailsBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(String message) {
        if(TextUtils.equals(message,"++")){
            page++;
            LoadMoreData();
        }else if(TextUtils.equals(message,"==")){
            page = 1;
            LoadMoreData();
        }
    }
}
